import { defineConfig } from '@vben/vite-config';
import { loadEnv } from 'vite';

export default defineConfig(async ({ command, mode }) => {
  const env = loadEnv(mode, process.cwd(), '');
  let proxyConfig: Record<string, any> | undefined = undefined;
  if (env.VITE_PROXY === 'true' && env.VITE_PROXY_CONFIG) {
    try {
      const parsedConfig = JSON.parse(env.VITE_PROXY_CONFIG);
      if (Array.isArray(parsedConfig)) {
        proxyConfig = {};
        for (const [prefix, target] of parsedConfig) {
          proxyConfig[prefix] = {
            target: target,
            changeOrigin: true,
            secure: false,
          };
        }
      }
    } catch (error) {
      console.error('Error parsing VITE_PROXY_CONFIG:', error);
    }
  }

  return {
    application: {},
    vite: {
      server: {
        proxy: proxyConfig,
      },
    },
  };
});
